package TestClient;

import java.net.*;
import java.util.Random;
import java.io.*;

/**
 * <pre>
 * @Package : TestClient
 * @File    : TestClient.java
 * <pre>
 *
 * @Author  : 차재우
 * @Date    : 2013. 7. 23.
 * @Version :
 */
public class TestClient {
	public static void main(String[] args) {
		new TestClient().RunClients();
	}
	
	private void RunClients() {
		int threadCnt = 20;
		
		Thread[] clientThread = new Thread[threadCnt];

		try {
			for(int i = 0 ; i < threadCnt ; i++) {
				clientThread[i] = new Thread(new ClientThread());
				clientThread[i].start();
				//Thread.sleep(GetRandomValue(3) * 1000);
			}
		} catch (Exception e) {
		}
	}
	
	private int GetRandomValue(int term) {
		return (1 + (int)(Math.random() * term));
	}

	/**
	 * <pre>
	 * @Package : TestClient
	 * @File    : TestClient.java
	 * <pre>
	 *
	 * @Author  : 차재우
	 * @Date    : 2013. 7. 23.
	 * @Version :
	 */
	class ClientThread implements Runnable {
		private byte[] sendBuf = null;
		private byte[] readBuf = null;

		public ClientThread() {

		}
		
		public void run() {
			Client();
		}

		private void Client() {
			try {
				String serverIp = "192.168.219.176";

				System.out.println("서버에 연결중입니다. 서버IP :" + serverIp);
				// 소켓을 생성하여 연결을 요청한다.
				Socket socket = new Socket(serverIp, 9872); 

				// 소켓의 입력, 출력 스트림			
				DataInputStream in = new DataInputStream(socket.getInputStream());
				DataOutputStream out = new DataOutputStream(socket.getOutputStream());
				
				// 전송할 테스트 데이터 생성
				MakeSendPacket();
				//System.out.print("Send data    : ");
				//DisplayBuffer(sendBuf);
				
				// 서버로 데이터 전송
				out.write(sendBuf);
				
				// 서버로부터 데이터 수신
				readBuf = new byte[32];
				in.read(readBuf, 0, 32);
				System.out.print("Receive data : ");
				DisplayBuffer(readBuf);

				// 스트림과 소켓을 닫는다.
				in.close();
				out.close();
				socket.close();
				System.out.println("연결이 종료되었습니다.");
			} catch(ConnectException ce) {
				ce.printStackTrace();
			} catch(IOException ie) {
				ie.printStackTrace();
			} catch(Exception e) {
				e.printStackTrace();
			}
		}
		
		private void MakeSendPacket() {		
			Random random = new Random();
			
			sendBuf = new byte[32];
			random.nextBytes(sendBuf);		
			sendBuf[0] = 0x21;
		}
		
		private void DisplayBuffer(byte[] buf) {
			for(int i = 0 ; i < buf.length ; i++)
				System.out.format("%02X  ", buf[i]);
			System.out.println("\n");
		}
	}
}
